import { createStore } from 'vuex'
import api from '@/api'

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || null,
    lotteryData: [],
    predictions: [],
    reports: {}
  },
  
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_LOTTERY_DATA(state, data) {
      state.lotteryData = data
    },
    SET_PREDICTIONS(state, predictions) {
      state.predictions = predictions
    },
    SET_REPORTS(state, reports) {
      state.reports = reports
    }
  },
  
  actions: {
    async login({ commit }, credentials) {
      try {
        console.log('[Store] 开始登录:', credentials.username)
        const response = await api.auth.login(credentials)
        console.log('[Store] 登录成功:', response.data)
        commit('SET_USER', response.data.user)
        commit('SET_TOKEN', response.data.access_token)
        return response
      } catch (error) {
        console.error('[Store] 登录失败:', error)
        throw error
      }
    },
    
    logout({ commit }) {
      commit('SET_USER', null)
      commit('SET_TOKEN', null)
    },
    
    async fetchLotteryData({ commit }, params) {
      try {
        const response = await api.lottery.getList(params)
        commit('SET_LOTTERY_DATA', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async updateLotteryData({ commit }) {
      try {
        const response = await api.lottery.update()
        return response
      } catch (error) {
        throw error
      }
    },
    
    async analyzeData({ commit }, params) {
      try {
        const response = await api.ai.analyze(params)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async verifyPrediction({ commit }, params) {
      try {
        const response = await api.ai.verify(params)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async fetchPredictions({ commit }, params) {
      try {
        const response = await api.ai.getPredictions(params)
        commit('SET_PREDICTIONS', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async fetchReports({ commit }, type) {
      try {
        const response = await api.reports.getReport(type)
        commit('SET_REPORTS', { ...this.state.reports, [type]: response.data })
        return response
      } catch (error) {
        throw error
      }
    }
  },
  
  getters: {
    isAuthenticated: state => !!state.token,
    user: state => state.user,
    lotteryData: state => state.lotteryData,
    predictions: state => state.predictions,
    reports: state => state.reports
  }
}) 